namespace SimpleWebServices.Configuration
{
    using System;
    using System.Xml;
    using System.Xml.Serialization;
    using SimpleWebServices.Data;
    using SimpleWebServices.Web;

    [XmlRoot("xml")]
    public sealed class XmlDataSetting
    {
        [XmlIgnore]
        public bool? Enabled
        {
            get
            {
                bool? value = null;

                if (!string.IsNullOrEmpty(this.EnabledValue))
                {
                    value = XmlConvert.ToBoolean(this.EnabledValue);
                }

                return value;
            }

            set
            {
                if (value.HasValue)
                {
                    this.EnabledValue = XmlConvert.ToString(value.Value);
                }
                else
                {
                    this.EnabledValue = null;
                }
            }
        }

        [XmlAttribute("enabled")]
        public string EnabledValue
        {
            get;
            set;
        }

        [XmlAttribute("path")]
        public string Path
        {
            get;
            set;
        }

        public void Upsert()
        {
            bool enabled = this.Enabled.HasValue ? this.Enabled.Value : true;

            if (enabled && !string.IsNullOrEmpty(this.Path))
            {
                string path = null;
                if (this.Path.StartsWith("~", StringComparison.Ordinal))
                {
                    path = HttpContextFactory.Current.Server.MapPath(this.Path.Substring(1));
                }
                else
                {
                    path = this.Path;
                }

                XmlDataObjectCollection.Load(path).Upsert();
            }
        }
    }
}